//
//  XRAudioProgressButton.m
//  Auditory
//
//  Created by 寒竹子 on 15/6/11.
//  Copyright (c) 2015年 寒竹子. All rights reserved.
//

#import "XRAudioProgressButton.h"
#import "Globle.h"

@interface XRAudioProgressButton ()

@property (nonatomic, strong) NSTimer * timer;

@end

@implementation XRAudioProgressButton

- (instancetype)initWithFrame:(CGRect)frame
                    backColor:(UIColor *)backColor
                progressColor:(UIColor *)progressColor
                    lineWidth:(CGFloat)lineWidth
{
    if (self = [super initWithFrame:frame]) {
        // 设置按钮的背景色为clearColor
        self.backgroundColor = [UIColor clearColor];
        
        _backColor = backColor;
        _progressColor = progressColor;
        _lineWidth = lineWidth;
    }
    
    return self;
}

/**
 * @brief  开启定时器
 *
 * @param
 *
 * @return
 */
- (void)startTimer
{
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.5f target:self selector:@selector(updateProgress) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}

/**
 * @brief  关闭定时器
 *
 * @param
 *
 * @return
 */
- (void)stopTimer
{
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
}

/**
 * @brief  更新播放进度 重绘进度条
 *
 * @param
 *
 * @return
 */
- (void)updateProgress
{
    _progress = [Globle sharedGloble].progress;
    
    [self setNeedsDisplay]; // 调用此方法重绘
}

/**
 * @brief  绘图
 *
 * @param
 *
 * @return
 */
- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
    
    // 绘制底部的back circle
    UIBezierPath * backPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(CGRectGetWidth(self.bounds) / 2.0f, CGRectGetHeight(self.bounds) / 2.0f) radius:(CGRectGetWidth(self.bounds) - _lineWidth) / 2.0f startAngle:(CGFloat)-M_PI_2 endAngle:(CGFloat)1.5 * M_PI clockwise:YES];
    
    // 设置画笔的颜色
    [_backColor setStroke];
    // 设置贝塞尔曲线的宽度
    backPath.lineWidth = _lineWidth;
    // 画底部的圆环
    [backPath stroke];
    
    // 绘制播放进度
    if (_progress) {
        UIBezierPath * progressPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(CGRectGetWidth(self.bounds) / 2.0f, CGRectGetHeight(self.bounds) / 2.0f) radius:(CGRectGetWidth(self.bounds) - _lineWidth) / 2.0f startAngle:(CGFloat)-M_PI_2 endAngle:(CGFloat)-M_PI_2 + _progress * M_PI * 2.0f clockwise:YES];
        [_progressColor setStroke];
        progressPath.lineWidth = _lineWidth;
        [progressPath stroke];
    }
}

@end
